#' @title 相关性热图ggplot版本
#' @description
#' @param cor_res `psych::corr.test()`运行结果
#' @param p_type p值类型，默认原始p值，可以换成 p.adj，校正后p值
#' @param saveFile 逻辑值，是否保存图片
#' @param var_name 文件名字
#' @param od 输出路径
#' @param fill_color 色块填充颜色默认`c("#0C6291",'white','#A63446')`
#' @param w 图宽
#' @param h 图高
#' @export
#' @return
#' @examples
#' @author *WYK*
#'
correlation_matrix_plot <- function(cor_res, p_type = "p", w = 6, h = 8, saveFile = T,
                                    od = NULL, var_name = "correlation_immune_xgene",
                                    fill_color = c("#0C6291",'white','#A63446')) {
    suppressMessages(library(tidyverse))
    suppressMessages(library(magrittr))
    library(scales)

    if (!is.null(od)) {
        if (!dir.exists(od)) {
            dir.create(od, recursive = T)
        }
    }

    if (any(is.na(cor_res$r[1, ]))) {
        na_variables = names(is.na(cor_res$r[1, ]))[which(is.na(cor_res$r[1, ]))] %>% paste0(collapse = ", ")

        cli::cli_alert_warning('{na_variables} 存在NA值，自动去除')
        cor_res$r = cor_res$r[, !is.na(cor_res$r[1, ])]
        cor_res[[p_type]] = cor_res[[p_type]][, !is.na(cor_res[[p_type]][1, ])]
    }

    df1 <- cor_res$r %>%
        as.data.frame() %>%
        rownames_to_column("gene") %>%
        pivot_longer(cols = -gene, names_to = "cell", values_to = "r")

    df2 <- cor_res[[p_type]] %>%
        as.data.frame() %>%
        rownames_to_column("gene") %>%
        pivot_longer(cols = -gene, names_to = "cell", values_to = "p")

    df <- inner_join(df1, df2) %>% mutate(p_sig = cut(p, c(-1, .01, .05, Inf), c("**", "*", '')))

    # df <- df %>% filter(gene == 'ATP6V1A')

    p <- df %>% ggplot(aes(x = cell, y = gene)) +
        geom_tile(aes(fill = r),color = 'white') +
        scale_fill_gradient2(
            low = fill_color[1],
            mid = fill_color[2],
            high = fill_color[3],
            limits = c(-1, 1)
        ) +
        geom_text(aes(label = p_sig), col = "black", size = 3.2,nudge_y = 0) +
        ggthemes::theme_hc() +
        theme(
            axis.title.x.bottom = element_blank(),
            axis.ticks.x.bottom = element_blank(),
            axis.ticks.y.left = element_blank(),
            axis.title.y.left = element_blank(),
            axis.text.x.bottom = element_text(
                angle = 45,
                hjust = 1, vjust = 1.1,size = 9
            ), legend.position = "top"
        ) +
        labs(fill = paste0("* p < 0.05", "  ", "** p < 0.01", "      ", "r"))

    if (isTRUE(saveFile)) {
        ggsave(plot = p, filename = str_glue("{od}{var_name}.pdf"), width = w, height = h)
    }

    return(p)
}


# 样式2
if (F) {
    df %>% mutate(p_if_sig = ifelse(p < .05, p, NA)) -> df

    p1 <- df %>%
        ggplot(aes(gene, cell, fill = r, label = format.pval(df[["p_if_sig"]], eps = .01, na.form = NA, digits = 1))) +
        geom_tile() +
        labs(x = NULL, y = NULL, fill = "r") +
        scale_fill_gradient2(mid = "#FBFEF9", low = "#0C6291", high = "#A63446", limits = c(-1, 1)) +
        geom_text(size = 2) +
        scale_x_discrete(expand = c(0, 0)) +
        scale_y_discrete(expand = c(0, 0)) +
        ggthemes::theme_hc() +
        theme(
            axis.title.x.bottom = element_blank(),
            axis.ticks.x.bottom = element_blank(),
            axis.ticks.y.left = element_blank(),
            axis.title.y.left = element_blank(),
            axis.text.x.bottom = element_text(
                angle = 90,
                hjust = 1, vjust = .5
            ), legend.position = "right"
        )

    plotout(
        od = "/Pub/Users/wangyk/project/Poroject/Molecular_ducking",
        name = "test", w = 6, h = 6, p = p1, plot_tif = FALSE
    )
}